package cn.assumejson.pro_netty.spring;

import org.slf4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * startup class
 *
 * @author by gang.Li 2022/3/12 0:38
 */
public class ApplicationMain {
    private static final Logger log = org.slf4j.LoggerFactory.getLogger(ApplicationMain.class);
    public static volatile boolean running = true;

    public static void main(String[] args) {
        try {

            AnnotationConfigApplicationContext ctx =
                    new AnnotationConfigApplicationContext("cn.assumejson.pro_netty.spring",
                            "cn.assumejson.pro_netty.example.controller",
                            "cn.assumejson.pro_netty.example.service");
            // 注册 优雅关闭钩子函数
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                try {
                    ctx.stop();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 更新spring 容器运行状态
                synchronized (ApplicationMain.class) {
                    running = false;
                    ApplicationMain.class.notify();
                }
            }));

            ctx.start();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }

        log.info("Service started successfully......");
        synchronized (ApplicationMain.class) {
            if (running) {
                try {
                    ApplicationContext.class.wait();
                } catch (InterruptedException ignored) {
                }
            }
        }
    }
}
